package com.shengwei.truck.driver.utils;

import com.shengwei.truck.driver.bean.MyDateTimeField;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * 工具类，封装了一些常用函数
 */
public class DateTimeUtils {
    private static final DecimalFormat DF = new DecimalFormat("######0.00");
    private static String TAG = "DateTimeUtils";
    public static final int MILLIS = 0; //毫秒
    public static final int SECOND = 1; //秒



    /**
     * 将date对象转换为 年月日
     * @param date
     * @return  年月日，如 2021-08-08"
     */
    public static String getYmdByDate(Date date){
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String strDate = simpleDateFormat.format(date);
            return strDate;
        } catch (Exception e) {
            return "";
        }
    }


    /**
     * 获得指定日期所在月的第1天的日期
     * @param date：指定日期
     * @return 月的第1天的日期
     */
    public static Date getMonthFirstDay(Date date){
        Calendar calendar = Calendar.getInstance();
        // 设置指定日期
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
        Date dateResult = calendar.getTime();
        MyLogCat.i(TAG,"getMonthFirstDay:"+getYmdByDate(dateResult));
        return dateResult;
    }

    /**
     * 获得指定日期所在月的最后1天的日期
     * @param date：指定日期
     * @return 月的最后1天的日期
     */
    public static Date getMonthEndDay(Date date){
        Calendar calendar = Calendar.getInstance();
        // 设置指定日期
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), 1);
        // 最后一天
        calendar.roll(Calendar.DATE, -1);
        Date dateResult = calendar.getTime();
        MyLogCat.i(TAG,"getMonthEndDay:"+getYmdByDate(dateResult));
        return dateResult;
    }


    /**
     * // 获取指定日期所在周的最后一天（周日）
     * @param date
     */
    public static Date getWeekEndDay(Date date){
        // 获取指定日期所在周的最后一天(周日)
        Calendar calendar = Calendar.getInstance();
        // 设置周一是第一天
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        // 设置指定日期
        calendar.setTime(date);

/*		// +0周一  +1周二  ...类推
		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
		 System.out.println("getWeekEndDay Calendar.DAY_OF_WEEK:"+dayOfWeek);*/
        //DAY_OF_WEEK表示一周中的第几天，它始终是从周日开始算的，如周四则是一周中的第5天

        calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek() + 6);
        Date resultDate = calendar.getTime();
        MyLogCat.i(TAG,"getWeekEndDay:"+getYmdByDate(resultDate));
        return  resultDate;
    }

    /**
     * // 获取指定日期所在周的第一天(周一)
     * @param date
     */
    public static Date getWeekFirstDay(Date date){

        // 获取指定日期所在周的第一天(周一)
        Calendar calendar = Calendar.getInstance();
        // 设置周一是第一天, getFirstDayOfWeek获取的默认是周日
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        // 设置指定日期
        calendar.setTime(date);
   /*	 int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
		 System.out.println("getWeekFirstDay Calendar.DAY_OF_WEEK:"+dayOfWeek);*/
        //DAY_OF_WEEK表示一周中的第几天，它始终是从周日开始算的，如周四则是一周中的第5天
        calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());

        Date resultDate = calendar.getTime();
        System.out.println("getWeekFirstDay:"+ getYmdByDate(resultDate));
        return resultDate;
    }
    /**
     * 检查结束时间 是否大于开始时间
     *
     * @param startDate  : 开始日期
     * @param startTime： 开始时分
     * @param endDate：   结束日期
     * @param endTime：   结束时分
     * @return
     */
    static public boolean checkEndTimeOK(String startDate, String startTime, String endDate, String endTime) {
        String start = startDate + " " + startTime + ":00";
        String end = startDate + " " + endTime + ":00";
        long startTimeStamp = toTimeStamp(start, MILLIS);
        long endTimeStamp = toTimeStamp(end, MILLIS);

        if (endTimeStamp <= startTimeStamp) {
            return false;
        }
        return true;
    }


    /**
     * 获取当前时间戳(单位：毫秒)
     *
     * @return
     */
    public static long getCurrentTimeMs() {
        return System.currentTimeMillis();
    }

    /**
     * 校验double数值是否为0
     *
     * @return
     */
    public static boolean isEqualToZero(double value) {
        return Math.abs(value - 0.0) < 0.01 ? true : false;
    }


    /**
     * 日期字符串转为时间戳
     *
     * @param time:    日期字符串，如2011-12-04 09:00:10
     * @param timeUnit ：转换为秒，还是毫秒
     * @return 秒或毫秒
     */
    public static long toTimeStamp(String time, int timeUnit) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        Date date;
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
        long timeStamp = date.getTime();

        if (timeUnit == SECOND) {
            timeStamp /= 1000;
        }
        return timeStamp;
    }

    /**
     * 把毫秒时间戳转为时分秒字符串
     *
     * @param timestamp 时间戳（单位：毫秒）
     * @return 10:01:55 时分秒字符串
     */
    public static String getHMS(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try {
            return sdf.format(new Timestamp(timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(timestamp);
    }

    /**
     * 把毫秒时间戳转为日期字符串如：2011-12-04 09:00:10
     *
     * @param timestamp 时间戳（单位：毫秒）
     * @return
     */
    public static String timeStampToDateString(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.format(new Timestamp(timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(timestamp);
    }

    /**
     * 把毫秒时间戳转为日期字符串如：2011-12-04 09:00:10
     *
     * @param timestamp 时间戳（单位：毫秒）
     * @return
     */
    public static String timeStampToDateNoHms(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.format(new Timestamp(timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(timestamp);
    }

    /**
     * 根据时间戳 获得 年月日时分秒等各字段的值，并封装成对象返回
     * @param timestamp
     * @return
     */
    public static MyDateTimeField getTimeFieldObject(long timestamp){
        String strDateTime = getDateTime(timestamp);

        String split[] = strDateTime.split("/");
        String []splitYmd = split[0].split("-");  //年月日
        int year = Integer.valueOf(splitYmd[0]);
        int month = Integer.valueOf(splitYmd[1]);
        int day = Integer.valueOf(splitYmd[2]);

        String []splitMhs = split[1].split(":"); //时分秒
        int hour = Integer.valueOf(splitMhs[0]);
        int min = Integer.valueOf(splitMhs[1]);
        int sec = Integer.valueOf(splitMhs[2]);

        MyDateTimeField myDateTimeField = new MyDateTimeField();
        myDateTimeField.year = year;
        myDateTimeField.month = month;
        myDateTimeField.day = day;
        myDateTimeField.hour = hour;
        myDateTimeField.min = min;
        myDateTimeField.second = sec;
        MyLogCat.i(TAG,myDateTimeField.toString());
        return myDateTimeField;
    }


    /**
     * 把毫秒时间戳转为年月日字符串如：2011-12-04
     *
     * @param timestamp
     * @return
     */
    public static String getDateTimeYMD(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.format(new Timestamp(timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(timestamp);
    }

    /**
     * 将浮点数保留2位小数
     *
     * @param doubleValue
     * @return
     */
    public static final String formatDouble(double doubleValue) {
        return DF.format(doubleValue);
    }


    /**
     * 获得当天0点的毫秒时间戳
     */
    public static long getZeroTimeStamp() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (long) (cal.getTimeInMillis());
    }

    /**
     * 获得当天最后1秒的 毫秒时间戳
     */
    public static long getTimesNight() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 24);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return  cal.getTimeInMillis();
    }



    /**
     * 将毫秒值 换算成 剩余时分秒
     *
     * @param milliseconds
     * @return
     */
    public static String getGapTime(long milliseconds) {
        int hours = (int) (TimeUnit.MILLISECONDS.toHours(milliseconds) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(milliseconds)));
        int minutes = (int) (TimeUnit.MILLISECONDS.toMinutes(milliseconds) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliseconds)));
        int seconds = (int) (TimeUnit.MILLISECONDS.toSeconds(milliseconds) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds)));

        StringBuffer timeResult = new StringBuffer();
        String strHour = String.valueOf(hours);
        String strMin = String.valueOf(minutes);
        String strSecond = String.valueOf(seconds);

        if (minutes < 10) {
            strMin = "0" + minutes;
        }
        if (seconds < 10) {
            strSecond = "0" + seconds;
        }
        timeResult.append(strHour).append(":")
                .append(strMin).append(":")
                .append(strSecond);

        return timeResult.toString();
    }

    /**
     * 获得当天0点时间
     */
    public static long getTimesmorningMs() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (long) (cal.getTimeInMillis());
    }


    /**
     * 获得任意1天的0点时间
     */
    public static long getMorningOneDay(int year,int month,int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR,year);
        cal.set(Calendar.MONTH,month);   //因为Calendar的月数是从0开始的
        cal.set(Calendar.DAY_OF_MONTH,day);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (long) (cal.getTimeInMillis());
    }
    public static long getEndTimeOneDay(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR,year);
        cal.set(Calendar.MONTH,month);   //因为Calendar的月数是从0开始的
        cal.set(Calendar.DAY_OF_MONTH,day);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.MILLISECOND, 0);
        return (long) (cal.getTimeInMillis());
    }
    /**
     * 获取年月日 时分秒中间+“/”
     *
     * @param timestamp
     * @return
     */
    public static String getDateTime(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss");
        try {
            return sdf.format(new Timestamp(timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(timestamp);
    }


}
